package com.design.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.design.config.CommonException;
import com.design.dao.entity.UserInfo;
import com.design.dao.mapper.UserInfoMapper;
import com.design.mapstruct.UserMapstruct;
import com.design.model.PageResult;
import com.design.model.UserInfoRequest;
import com.design.model.UserInfoResponse;
import com.design.model.UserInfoUpdateRequest;
import com.design.service.ManageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 查询用户列表
     *
     * @param name     用户名
     * @param gender   性别
     * @param pageNum  页序号
     * @param pageSize 页大小
     * @return 用户列表
     */
    @Override
    public PageResult<List<UserInfoResponse>> queryByPage(String carNum, byte userType, String name, Integer gender, Integer pageNum, Integer pageSize) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        wrapper.eq("user_type", userType);
        wrapper.orderByDesc("id");
        if (StringUtils.isNoneBlank(name)) {
            wrapper.eq("user_name", name);
        }
        if (StringUtils.isNoneBlank(carNum)) {
            wrapper.eq("car_num", carNum);
        }
        if (gender != null) {
            wrapper.eq("gender", gender);
        }
        Page<UserInfo> responseList = userInfoMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return new PageResult<>(UserMapstruct.INSTANCE.toUserResponse(responseList.getRecords()), responseList.getTotal());
    }

    /**
     * 查询用户列表
     *
     * @param id 帐号
     * @return 用户详情
     */
    @Override
    public UserInfoResponse queryById(Long id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        return UserMapstruct.INSTANCE.toUserResponseEntity(userInfo);
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     * @return 删除结果
     */
    @Override
    public void deleteById(long id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (null == userInfo) {
            throw new CommonException("用户不存在");
        }
        userInfoMapper.deleteById(id);
    }


    /**
     * 管理员添加用户
     *
     * @param userInfoRequest 用户信息
     */
    @Override
    public void saveUser(UserInfoRequest userInfoRequest) {
        // 1.数据初始化
        Date now = new Date();
        UserInfo userInfo = UserMapstruct.INSTANCE.toUserInfoEntity(userInfoRequest);
        userInfo.setUpdateTime(now);
        userInfo.setStatus(true);

        // 2.新增数据
        if (userInfoRequest.getId() == null) {
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserInfo::getPhone, userInfoRequest.getPhone());
            queryWrapper.eq(UserInfo::getIsDelete, 0);
            if(!CollectionUtils.isEmpty(userInfoMapper.selectList(queryWrapper))){
                throw new CommonException("该手机号已经注册");
            }

            LambdaQueryWrapper<UserInfo> queryWrapperIdNum = new LambdaQueryWrapper<>();
            queryWrapperIdNum.eq(UserInfo::getIdNum, userInfoRequest.getIdNum());
            queryWrapperIdNum.eq(UserInfo::getIsDelete, 0);
            if(!CollectionUtils.isEmpty(userInfoMapper.selectList(queryWrapperIdNum))){
                throw new CommonException("该证件号已经注册");
            }

            LambdaQueryWrapper<UserInfo> queryWrapperCarNum = new LambdaQueryWrapper<>();
            queryWrapperCarNum.eq(UserInfo::getCarNum, userInfoRequest.getCarNum());
            queryWrapperCarNum.eq(UserInfo::getIsDelete, 0);
            if(!CollectionUtils.isEmpty(userInfoMapper.selectList(queryWrapperCarNum))){
                throw new CommonException("该车牌号已经注册");
            }

            // 持久化用户
            userInfo.setCreateTime(now);
            userInfoMapper.insert(userInfo);
            return;
        }

        // 3.更新
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 修改密码
     *
     * @param request 密码
     * @return 修改结果
     */
    @Override
    public void updatePassword(UserInfoUpdateRequest request) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        wrapper.eq("phone", request.getPhone());
        List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(userInfos)) {
            throw new CommonException("用户信息不存在");
        }
        UserInfo userInfo = userInfos.get(0);

        if(!userInfo.getPassword().equals(request.getOld())){
            throw new CommonException("旧密码错误");
        }

        if (StringUtils.isBlank(request.getOld()) || !request.getNewWord().equals(request.getRepeat())) {
            throw new CommonException("修改密码失败，请重新输入");
        }


        userInfo.setPassword(request.getNewWord());
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 修改手机
     *
     * @param request 手机
     * @return 修改结果
     */
    @Override
    public void updatePhone(UserInfoUpdateRequest request) {


        if (StringUtils.isBlank(request.getOld()) || !request.getNewWord().equals(request.getRepeat())) {
            throw new CommonException("修改密码失败，请重新输入");
        }


        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        wrapper.eq("phone", request.getOld());
        List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(userInfos)) {
            throw new CommonException("用户信息不存在");
        }
        UserInfo userInfo = userInfos.get(0);


        userInfo.setPhone(request.getNewWord());
        userInfoMapper.updateById(userInfo);
    }
}
